<template>
	<div class="yolo-model">
		<el-form>
			<el-row :gutter="24">
				<el-col :span="6">
					<el-form-item label="模型版本">
						<el-select
							v-model="form.currentModel"
							placeholder="请选择"
							@change="switchModel"
						>
							<el-option
								v-for="item in modelList"
								:key="item"
								:label="item"
								:value="item"
							/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item :label="`置信度(${form.confidence})`">
							<el-slider
								v-model="form.confidence"
								:max="1"
								:min="0.1"
								:step="0.01"
							/>

					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="24">
				<el-col>
					<el-form-item label="显示类型">
						<el-checkbox-group v-model="form.show_category">
							<el-checkbox
								v-for="item in modelInfos"
								:key="item"
								:label="item"
							/>
						</el-checkbox-group>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>

		<el-card class="upload-card">
			<el-upload
				ref="uploadRef"
				class="video-upload"
				action="/api/yolo_model/videoRecognition/"
				:data="uploadFormData"
				:limit="3"
				:multiple="true"
				:disabled="hasPendingTasks"
			drag
			:auto-upload="true"
			:show-file-list="false"
			:on-success="handleUploadSuccess"
			:on-error="handleUploadError"
			:on-exceed="handleExceed"
			:before-upload="beforeUpload"
			>
			<el-button
				type="primary"
				:disabled="hasPendingTasks"
			>
			{{ hasPendingTasks ? '处理中，请等待...' : '上传视频' }}
			</el-button>
			<template #tip>
				<div class="upload-tip">
        <span v-if="hasPendingTasks" style="font-size: 30px;">
          有{{ pendingCount }}个视频正在处理中，请完成后上传
        </span>
					<span v-else>支持MP4/AVI格式，最多同时上传3个</span>
				</div>
			</template>
			</el-upload>
		</el-card>

		<el-card class="history-card">
			<el-table :data="historyList" v-loading="historyLoading">
				<el-table-column prop="filename" label="文件名" width="200" />
				<el-table-column prop="status" label="状态" width="120">
					<template #default="{ row }">
						<el-tag :type="getStatusType(row.status)">
							{{ row.status }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="create_time" label="上传时间" width="180" />
				<el-table-column label="操作">
					<template #default="{ row }">
						<el-button
							v-if="row.status === '识别成功'"
							type="primary"
							size="small"
						>
							查看结果
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount,nextTick } from 'vue'
import {
	ElMessage,
	ElNotification,
	type UploadInstance,
	type UploadRawFile
} from 'element-plus'
import {
	modelVersions,
	changeModel,
	yoloModelInfo,
	videoRecognitionList
} from '/@api/yolo_model/hz-system-yolo-model-api'

// 表单数据
const form = reactive({
	currentModel: '',
	confidence: 0.5,
	show_category: [] as string[]
})

// 上传相关状态
const uploadRef = ref<UploadInstance>()

// 新增计算属性
const pendingCount = computed(() =>
	historyList.value.filter(item => item.status === '识别中').length
)
// 新增超出限制处理
const handleExceed = () => {
	ElMessage.warning('请等待当前视频处理完成后再上传')
}
// 历史记录
const historyList = ref<any[]>([])
const historyLoading = ref(false)

// 轮询定时器
let pollingTimer: NodeJS.Timeout | null = null

// 计算属性
const uploadFormData = computed(() => ({
	...form,
	show_category: form.show_category.join(',')
}))

// 生命周期
onMounted(() => {
	initData()
	startPolling()
})

onBeforeUnmount(() => {
	stopPolling()
})

const modelList = ref([])
const modelInfos = ref([])
// 初始化数据
const initData = async () => {
	try {
		// 获取模型列表
		const modelRes = await modelVersions()
		modelList.value = modelRes.data.model_version
		form.currentModel = modelList.value[0]

		// 获取模型信息
		const infoRes = await yoloModelInfo()
		modelInfos.value = Object.values(infoRes.data.supported_classes)
		form.show_category = [...modelInfos.value]

		// 加载历史记录
		await loadHistory()
	} catch (error) {
		ElMessage.error('初始化数据失败')
	}
}

// 上传处理
const beforeUpload = (file: UploadRawFile) => {
	if (hasPendingTasks.value) {
		ElMessage.warning('请等待当前视频处理完成后再上传')
		return false
	}

	nextTick(() => {
		uploadRef.value?.clearFiles()
	})
	return true
}



const handleUploadSuccess = (response: any) => {
	if (response.code === 200) {
		ElMessage.success('视频已加入处理队列')
		loadHistory()
		startPolling()
	} else {
		ElMessage.error(response.msg)
	}

	// 强制更新DOM
	uploadRef.value?.clearFiles()
}

const handleUploadError = () => {
	ElMessage.error('视频上传失败')
}

// 历史记录操作
const loadHistory = async () => {
	try {
		historyLoading.value = true
		const res = await videoRecognitionList({
			page: 1,
			page_size: 10
		})
		historyList.value = res.data.records
	} catch (error) {
		ElMessage.error('获取识别历史失败')
	} finally {
		historyLoading.value = false
	}
}

// 轮询逻辑
const hasPendingTasks = computed(() =>
	historyList.value.some(item => item.status === '识别中')
)

const startPolling = () => {
	if (!pollingTimer) {
		pollingTimer = setInterval(async () => {
			await loadHistory()
			if (!hasPendingTasks.value) {
				stopPolling()
				ElNotification.success('所有视频处理完成，可以继续上传')
			}
		}, 3000)
	}
}

const stopPolling = () => {
	if (pollingTimer) {
		clearInterval(pollingTimer)
		pollingTimer = null
	}
}

// 状态样式
const getStatusType = (status: string) => {
	switch (status) {
		case '识别中': return 'warning'
		case '识别成功': return 'success'
		case '识别失败': return 'danger'
		default: return 'info'
	}
}

// 模型切换
const switchModel = async (model: string) => {
	try {
		const res = await changeModel(model)
		ElMessage({
			type: res.code === 200 ? 'success' : 'error',
			message: res.msg,
			duration: 2000
		})
	} catch (error) {
		ElMessage.error('模型切换失败')
	}
}
</script>

<style lang="scss" scoped>
.yolo-model {
	padding: 20px;
	height: calc(100vh - 60px);
	overflow-y: auto;

	.confidence-container {
		display: flex;
		align-items: center;
		gap: 12px;

		.confidence-value {
			min-width: 40px;
			text-align: right;
		}
	}

	.upload-card {
		margin-top: 20px;

		.upload-tip {
			color: #666;
			font-size: 12px;
			margin-top: 8px;
		}
	}

	.history-card {
		margin-top: 20px;

		:deep(.el-table__row) {
			transition: background-color 0.3s;

			&:hover {
				background-color: #f5f7fa;
			}
		}
	}
}
</style>
<style lang="scss">
/* 新增禁用状态样式 */
:deep(.el-upload__dragger.is-disabled) {
	cursor: not-allowed;
	border-color: #ddd;
	background-color: #f5f7fa;

	&:hover {
		border-color: #ddd;
	}
}

.upload-tip {
	color: var(--el-color-danger);

	span {
		display: block;
		margin-top: 8px;
	}
}
</style>
